import { Table, Alert,Card,Form ,Button,message,Divider,Pagination,Popconfirm,Icon,Switch} from 'antd';
import React, { Component , Fragment} from 'react';
import Column from 'antd/lib/table/Column';
import { connect } from 'dva';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './index.less';
import Update from './components/Update';
import RightContent from '@/components/GlobalHeader/RightContent';
//注入模型类 dispatch
const mapStateToProps = (state) => {
    const menuList = state['AdminMenu'].menuList;
    const menuData = state['AdminMenu'].menuData;
    const ParentData = state['AdminMenu'].ParentData;
    //console.log('aa',state);
    return {
      menuList,
      menuData,
      ParentData,
    };
};

//把from对象加入到this.props里面
@Form.create()
@connect(mapStateToProps)
export default class menu extends Component {
    //这个地方比较重要 页面加载完成之后的参数初始化
    state = {
        refaultData:{},
        //初始化modal 状态 false为关闭
        modalVisible:false,
        modalTitle:'新增路由',
        confirmLoading:false,//modal确认按钮loading
        loading: false,//列表加载状态
        rowKey:'id',//列表主键
        rowKeyValue:0,//当前选择主键值
        operationType:'insert',//操作类型
        modalLoading:false,
        removeId:[],//删除资源的默认ID
        selectedRowKeys:[],//列表全选
        removeButtonLoading: false,//删除按钮加载状态
    }
    /**
     * 前置函数 在页面加载时就执行的函数
     */
    componentDidMount = () => {
        this.getFetch();//初次加载
    }
    /**
     * 列表自定义方法
     */
    handleTableChange = (pagination, filters, sorter) => {
        //console.log('sort');
        const pager = { ...this.state.pagination };
        pager.current = pagination.current;
        this.setState({
          pagination: pager,
        });
        this.getFetch({
          pageSize: pagination.pageSize,
          page: pagination.current,
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...filters,
        });
    };
    /**
     * 列表数据获取
     */
    getFetch = (params = {}) =>{
        //加载中
        this.setState({ loading: true });
        const { dispatch } = this.props;
        dispatch({
            type: 'AdminMenu/select',
            payload:params,
        });
        //加载中取消
        setTimeout(() => {
          this.setState({ loading: false });
        },500);
    };
    getFind=(id=0)=>{
      this.setState({
        modalLoading:true
      });
      const { dispatch } = this.props;
      const param = {
        id:id
      }
      dispatch({
          type: 'AdminMenu/find',
          payload: param,
          callback:(e)=>{
            setTimeout(() => {
              this.setState({
                modalLoading:false
              });
            }, 10);
          }
      });
      
    }
    /**
     * 获取父路由数据
     */
    getParentSelect=(id=0)=>{
      this.setState({
        modalLoading:true
      });
      const { dispatch } = this.props;
      const param = {
        id:id
      }
      dispatch({
          type: 'AdminMenu/parentSelect',
          payload: param,
          callback:(e)=>{
            setTimeout(() => {
              this.setState({
                modalLoading:false
              });
            }, 10);
          }
      });
    }
    //这个函数比较重要
    /**
     * 主要用于关闭modal
     * flag参数true为显示modal false为关闭modal
     */
    handleModalVisible = (flag=false,id=0) => {
      //console.log('datas',this.props.ParentData);
      this.getFind(id);
      this.getParentSelect(id);
        if(id === 0){
          //参数重置
          this.setState({
            rowKeyValue:0,
            operationType:'insert'
          });
        }else{
          //参数重置
          this.setState({
            rowKeyValue:id,
            operationType:'edit'
          });
        }
        
        //const flags = flag===true?false:true;
        this.setState({
          modalVisible: flag,
        });
    };
    /**
     * 删除某个路由
     */
    onDelete = (e,callback2) =>{
      //console.log('aaaa',this.state.removeId);
      const id = this.state.removeId;
      const { dispatch } = this.props;
      //这里进行了和服务端进行交互需要写模型
      dispatch({
        type: 'AdminMenu/remove',
        payload: {id:id},
        callback:(e)=>{
          if(e.code===1){
            setTimeout(() => {
              this.getFetch();
            }, 10);
          }else{
            message.error(e.msg);
          }
          (callback2 && typeof(callback2) === "function") && callback2();
        }
      });

    }
    /**
     * 本函数主要用户处理新增表单提交数据保存
     * 和服务端进行交互时用到
     */
    onSubmit = (fields) => {
      
        this.setState({
          confirmLoading:true
        });
        console.log('bbbbb',this.state.confirmLoading);
        const { dispatch } = this.props;
        //这里进行了和服务端进行交互需要写模型
        console.log('this.state.operationType',this.state.operationType);
        if(this.state.operationType === "insert"){
          dispatch({
              type: 'AdminMenu/insert',
              payload: fields,
              callback:(e)=>{
                setTimeout(() => {
                  this.getFetch();
                  this.handleModalVisible(false);
                  this.setState({ confirmLoading: false });
                }, 10);
              }
          });
        }else{
          dispatch({
              type: 'AdminMenu/edit',
              payload: {id:this.state.rowKeyValue,...fields},
              callback:(e)=>{
                setTimeout(() => {
                  this.getFetch();
                  this.handleModalVisible(false);
                  this.setState({ confirmLoading: false });
                }, 10);
              }
          });
        }
    };
    onSelectChange = selectedRowKeys => {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.setState({ selectedRowKeys });
    };
    /**
     * 渲染页面
     */
    render (){
        /**
         * 这个地方是写的本地数据，等后面新增弄好了就和服务端获取数据
         */
        const data = [{
            key: '1',
            name: '胡彦斌',
            age: 32,
            address: '西湖区湖底公园1号'
          }, {
            key: '2',
            name: '胡彦祖',
            age: 42,
            address: '西湖区湖底公园1号'
          }];
          /**
           * 表单头部
           */
        //   const column = [
        //     {
        //         title:'地址',
        //         dataIndex:'address'
        //     },
        //     {
        //         title:'年龄',
        //         dataIndex:'age'
        //     },
        //     {
        //         title:'姓名',
        //         dataIndex:'name'
        //     },
        //     {
        //         title:'key',
        //         dataIndex:'key'
        //     }
        //   ];
          const column = [
            // {
            //   title:'id',
            //   dataIndex:'id',
            //   sorter: true,
            // },
            {
                title:'名称',
                dataIndex:'name',
                sorter: false,
            },
            {
                title:'图标',
                dataIndex:'icon',
                sorter: true,
            },
            {
                title:'路径',
                dataIndex:'path',
                sorter: true,
            },
            {
                title:'地址',
                dataIndex:'component',
                sorter: true,
            },
            {
                title:'是否显示子菜单',
                dataIndex:'hideChildrenInMenu',
                filters: [{ text: '显示', value: 1 }, { text: '隐藏', value: 0 }],
                width: '20%',
                render: (text, record) => (
                  <Switch checkedChildren="显示" unCheckedChildren="隐藏" defaultChecked={record.hideChildrenInMenu==1?true:false} />
                )
            },
            {
                title:'是否显示',
                dataIndex:'hideInMenu',
                filters: [{ text: '显示', value: 1 }, { text: '隐藏', value: 0 }],
                width: '20%',
                render: (text, record) => (
                  <Switch checkedChildren="显示" unCheckedChildren="隐藏" defaultChecked={record.hideInMenu==1?true:false} />
                )
            },
            {
                title:'是否启用',
                render: (text, record) => (
                  <Switch checkedChildren="启用" unCheckedChildren="禁用" onChange={()=>{
                    this.props.dispatch({
                      type: 'AdminMenu/setField',
                      payload: {id:record['id'],value:(record['status']==1?0:1),field:'status'},
                      callback:(e)=>{
                        setTimeout(() => {
                          this.getFetch();
                          this.setState({ refaultData: e });
                        }, 10);
                      }
                  });
                  }} defaultChecked={record.status==1?true:false} />
                )
            },
            {
                title: '操作',
                render: (text, record) => (
                  <Fragment>
                    <a onClick={() => {
                      this.setState({
                        rowKeyValue:record[this.state.rowKey],
                        operationType:'edit'
                      });
                      this.handleModalVisible(true,record[this.state.rowKey]);
                    }}>编辑</a>
                    <Divider type="vertical" />
                    <Popconfirm
                      title={`确定要删除[${record['name']}]包括下方所有子路由？`}
                      icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
                      onConfirm={this.onDelete}
                    >
                      <a href="#" onClick={() => {
                        this.setState({
                          removeId:[record['id']]
                        });
                      }}>删除</a>
                    </Popconfirm>
                  </Fragment>
                ),
            }
          ];
          
          const { data1 }= {};
        // rowSelection objects indicates the need for row selection
        //这个地方万恶的文档居然没写
        /**
         * 列表多选操作
         */
        // const rowSelection = {
        //     //单个取消
        //     onChange: (selectedRowKeys, selectedRows) => {
        //     console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        //     },
        //     //单个选中
        //     onSelect: (record, selected, selectedRows) => {
        //     console.log(record, selected, selectedRows);
        //     },
        //     //所有选中 & 取消
        //     onSelectAll: (selected, selectedRows, changeRows) => {
        //     console.log(selected, selectedRows, changeRows);
        //     },
        // };
        const { removeButtonLoading, selectedRowKeys } = this.state;
        const rowSelection = {
          selectedRowKeys,
          onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        /**
         * 初始化modal 需要用到的参数
         */
        const parentMethods = {
            //modal 点击确定处理函数
            onSubmit: this.onSubmit,
            //modal 点击关闭处理函数
            handleModalVisible: this.handleModalVisible,
          };
          const {menuList} = this.props;
          const { list = [], pagination = false } = menuList || {};
          //console.log('uuuuuuuuuuuuuuuuuuuu',this.props);
        return (
            <PageHeaderWrapper>
                <Card bordered={false} className={styles.tableList}>
                    <div style={{ marginBottom: 16 }}>
                    <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)} className={styles.submitButtons}>
                        新建
                    </Button>
                    <Button type="primary" onClick={() => {
                        this.setState({
                          removeButtonLoading:true,
                          removeId:this.state.selectedRowKeys
                        });
                        this.onDelete({}, ()=>{this.setState({
                          selectedRowKeys: [],
                          removeButtonLoading: false,
                        })});
                      }} disabled={!hasSelected} loading={removeButtonLoading}>
                      批量删除
                    </Button>
                    <span style={{ marginLeft: 8 }}>
                      {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
                    </span>
                    </div>
                    <div>
                        <Table
                        rowSelection={rowSelection}
                        dataSource={list}
                        rowKey="id"
                        bordered={true}
                        pagination={false}
                        columns={column}
                        loading={this.state.loading}
                        onChange={this.handleTableChange}
                        defaultExpandAllRows={true}
                        />
                        <Pagination 
                        className={styles.Pagination}
                        showSizeChanger
                        defaultCurrent={3}
                        total={500}
                        />
                    </div> 
                </Card>
                <Update {...parentMethods} modalVisible={this.state.modalVisible} form={this.props.form} confirmLoading={this.state.confirmLoading} menuData={this.props.menuData} modalTitle={this.state.modalTitle} modalLoading={this.state.modalLoading} ParentData={this.props.ParentData} />
            </PageHeaderWrapper>
        )
    }
    
};